/*
 * Copyright 2010 Michael Nitsche
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package de.mnit.basis.daten.struktur.container;

import de.mnit.basis.daten.struktur.Warteschlange;

/**
 * @author Michael Nitsche
 * Um eine Variable gleichzeitig mehreren Threads sauber bereitstellen zu können
 *
 * Evtl. noch realisieren, daß beliebige Lesevorgänge parallel möglich sind,
 * außer wenn jemand schreibt. Und nur je einen Schreibvorgang
 */
public final class Engpass<T> implements S_Kiste<T> {

	private T wert=null;
	private Warteschlange<Thread> warteliste;
	private int anzahl=0;


	public Engpass(T startwert) {
		this.warteliste=Warteschlange.neu();
		this.wert=startwert;
	}


	public static <T> Engpass<T> neu()              { return new Engpass<T>(null); }
	public static <T> Engpass<T> neu(T startwert)   { return new Engpass<T>(startwert); }


	public synchronized void s(T t) {
		lock();
		wert=t;
		unlock();
	}

	public synchronized T g() {
		lock();
		final T erg=wert;
		unlock();
		return erg;
	}

	public String toString() {
		return this.getClass().getSimpleName()+"("+this.g()+")"; //Klasse.gName(this)
	}

	// INTERN

	private synchronized void lock() {
		if( anzahl>0 ) {
			Thread t=Thread.currentThread();
			this.warteliste.plus(t);
			try {
				t.wait();
			}
			catch( InterruptedException e ) {}
		}
		anzahl++;
	}

	private synchronized void unlock() {
		anzahl--;
	    if( anzahl > 0 )
	    	this.warteliste.gNaechstes().notify();
	}

}
